<template>
  <base-page-view :class-name="'gift-bag-page '+(titleIndex?'bottom':'')">
    <base-nav :title="titleList[titleIndex]">
      <view slot="left" class="header-left" @click="handelBack">
        <image src="/static/images/icon/icon_arror_left.png" />
      </view>
    </base-nav>
    <template v-if="pageLoaded">
      <template v-if="boxList.length">
        <!-- 箱起礼包列表 -->
        <view v-if="titleIndex===0" class="box-list">
          <div v-for="(item, idx) in boxList" :key="idx" class="box-item" @click="setGoods(item)">
            <div class="image-box">
              <b-image class-name="main-pic" :src="item.box_bonus_gift.image_main" mode="aspectFill" />
            </div>
            <view class="main-text">
              <view class="text">{{ item.goods.title }}</view>
              <view class="details">
                <image class="details-icon" src="/static/images/icon/icon_more_list.png" mode="aspectFit" />
              </view>
            </view>
          </div>
        </view>
        <!-- 选择箱起商品 -->
        <view v-if="titleIndex!==0" class="form">
          <view class="form-title">{{ goods.title }}</view>
          <view class="form-content">
            <view v-for="(item, index) in gifts" :key="index" class="gifts-item">
              <view class="goods-item">
                <view @click="navigateToDeatil(item)">
                  <b-image class-name="goods-pic" :src="item.goodsImage" mode="aspectFill" />
                </view>
                <view class="goods-content">
                  <view class="title" @click="navigateToDeatil(item)">{{ item.goodsName }}</view>
                  <view class="money-item">
                    <text>￥<text class="big-money">{{ item.regionPrice | formatMoney }}</text></text>
                    <base-stepper :value="item.num" :min="0" :max="stock_number || 1" :size="34" :border-radius="4" @change="cartNumChange($event,index)"></base-stepper>
                  </view>
                </view>
              </view>
              <view v-if="item.presentGoods.length>0" class="gift-tips">
                <view class="title">
                  <text>赠品：<text v-for="(subItem, subIndex) in item.presentGoods" :key="subIndex">{{ subItem.giveRemark }}</text></text>
                  <!-- <text>{{ item.presentGoods[0].giveRemark }}</text> -->
                </view>
              </view>
            </view>
          </view>
        </view>
        <view v-if="titleIndex!==0 && markupGoodses.length !== 0" class="add-con">
          <view class="form-title">
            <text>加小钱得好礼</text>
            <text class="title-tip">（加购商品只可选择一种）</text>
          </view>
          <view class="form-content">
            <view v-for="(item, index) in markupGoodses" :key="index" class="gifts-item">
              <view class="goods-item">
                <image class="icon_gou" :src="index === current ? '/static/images/icon/icon_radio_active.png' :'/static/images/icon/icon_radio.png'" @click.stop="selEvent(index)" />
                <view class="img-con">
                  <b-image :src="item.image" mode="aspectFill" />
                  <!-- <image v-if="item.status === 5" src="/static/images/common/img_status_5.png" class="drop-img" mode="aspectFit" /> -->
                </view>
                <view class="goods-content">
                  <view :class="['title', {'gray-text':current !== index || item.status === 5}]">{{ item.name }}</view>
                  <view :class="['goods-sku', {'gray-text':current !== index || item.status === 5}]" @click.stop="goSelSku(index, true)">
                    <text v-if="item.skuName">{{ item.skuName }}</text>
                    <text v-else>请选择规格</text>
                    <image class="right-icon" src="/static/images/inventory/arrow_left.png" mode="aspectFit" />
                  </view>
                  <view class="money-item">
                    <view class="text-flex">
                      <view v-if="item.status === 5" class="drop-text">已下架</view>
                      <text :class="{'gray-text':current !== index || item.status === 5}">￥<text :class="['big-money', {'gray-text':current !== index || item.status === 5}]">{{ item.price | formatMoney }}</text></text>
                    </view>
                    <base-stepper v-if="index === current" :value="item.count" :min="1" :max="item.selectedSkuItem && item.selectedSkuItem.order_min ? item.selectedSkuItem.order_min : 999999" :size="34" :border-radius="4" @change="changeQuantity($event,index)" @disable="alertMax"></base-stepper>
                    <base-stepper v-else :value="0" :min="0" :max="0" :size="34" :border-radius="4"></base-stepper>
                  </view>
                </view>
              </view>
              <view v-if="item.limit_buy_tips" :class="['gift-tips', {'gray-area':current !== index || item.status === 5}]">
                <view class="title">
                  {{ item.limit_buy_tips }}
                </view>
              </view>
            </view>
          </view>
        </view>
        <!-- 底部 -->
        <footer-bar v-if="titleIndex!==0">
          <view class="footer-content">
            <view class="view-freight" @click="$navigateTo(`/pagesDetail/commodity/freight-calculate?bonus_gift_id=${box_bonus_gift.bonus_gift_id}`)">
              <view>点击查看运费测算明细</view>
              <image class="right-icon-orange" src="/static/images/inventory/right_icon_orange.png" mode="aspectFit" />
            </view>
            <view class="btn-line">
              <view class="btn" @click="handleSubmit">立即提交</view>
            </view>
          </view>
        </footer-bar>
        <base-popup :show="pShow" whole-mask :show-close="false" @close="closePopup">
          <view
            v-if="selGoods && selGoods.sku_list && hold"
            class="maskContainer shopCartMask"
            @touchmove.prevent>
            <view class="cartClose" @click="closePopup">
              <image src="/static/images/icon/icon_close.png" />
            </view>
            <view class="cartMain">
              <view class="goodsImg">
                <b-image width="180" mode="aspectFill" height="180" :src="selectedSkuItem ? selectedSkuItem.goods_pic : selGoods.image" />
              </view>
              <view class="priceBox">
                <view class="price">
                  <view class="span"><view class="b">¥</view>{{ (_getUserLevel(selectedSkuItem || selGoods)) | formatMoney }}</view>
                </view>
                <view class="skuDec">{{ selectedSkuItem ? `已选择: "${selectedSkuItem.selectText ? selectedSkuItem.selectText + ';' : ''}  ${buyCount}件"` : '请选择' }}</view>
              </view>
            </view>
            <sku-list :sku-origin="selGoods" :sku-list="selGoods.sku_list" @selectedItem="changeSkuItem"></sku-list>
            <view v-if="maskType !== 'packSelect' && maskType !== 'presentSelect'" class="cartCount">
              <view class="title">购买数量
                <view v-if="selectedSkuItem && selectedSkuItem.order_limit !== 0" class="small">
                  (限购{{ selectedSkuItem.order_limit }}件)
                </view>
              </view>
              <view style="height: 42rpx">
                <base-stepper :value.sync="buyCount" :border-radius="0" :size="42" :min="1" :max="selectedSkuItem && selectedSkuItem.order_min ? selectedSkuItem.order_min : 999999" @change="changeQuantity($event)" @disable="alertMax"></base-stepper>
              </view>
            </view>
            <view class="cartBut maskBottomBtn" :class="{'gray': !selectedSkuItem}" @click="cartConfirm">确认</view>
          </view>
        </base-popup>
      </template>
      <!-- empty -->
      <view v-else class="empty-content">
        <msg-page type="empty_list" text="暂无可用于提货的商品" btn-text="返回" @btnClick="handelBack"></msg-page>
      </view>
    </template>
  </base-page-view>
</template>
<script>
import baseStepper from '@/components/base/base-stepper.vue'
import msgPage from '@/components/msgPage/index.vue'
import footerBar from '@/components/footerBar/index.vue'
import SkuList from '../components/commodity-sku.vue'
import { getUserLevel } from '@/utils/common'

import './index.scss'
export default {
  name: 'GiftBag',
  components: {
    baseStepper,
    msgPage,
    footerBar,
    SkuList
  },
  data() {
    return {
      sdf: 1,
      pageLoaded: false,
      pageQuery: {},
      titleList: ['箱起提货', '选择提货商品'],
      titleIndex: 0,
      stock_number: 0,
      boxList: [],
      box_bonus_gift: {},
      goods: {},
      markupGoodses: [],
      selGoods: {},
      gifts: [],
      current: -1, // 当前勾选加购商品下标
      cartTotalNum: 0, // 总活动商品数
      pShow: false,
      selectedSkuItem: {}, // 当前选中的sku项数据
      buyCount: 1, // 规格选择弹窗中的商品数
      groupInfo: {
        groupPrice: 0
      },
      commodityType: 'boxGoods',
      maskType: 'singleGoods',
      hold: true,
      isBoxGoodsPackage: false // 箱起套餐
    }
  },
  onLoad(options) {
    this.pageQuery = options
    this.fetchData()
    this.getStockNum()
  },
  methods: {
    // 获取页面数据
    async fetchData() {
      const res = await this.$api.mineApi.stockGoods({
        series_id: this.pageQuery.series_id
      })
      if (res.success) {
        this.boxList = res.data || []
        this.current = -1
        this.cartTotalNum = 0
        if (this.boxList.length === 1) {
          this.titleIndex = 1
          this.box_bonus_gift = this.boxList[0].box_bonus_gift
          this.goods = this.boxList[0].goods
          this.gifts = (this.boxList[0].gifts || []).map(i => ({ ...i, num: 0 }))
          this.markupGoodses = this.boxList[0].markup_goodses || []
        }
      }
      this.pageLoaded = true
    },
    // 查询云仓库存信息
    async getStockNum() {
      const res = await this.$api.mineApi.getStockNum({ ...this.pageQuery })
      if (res.success) {
        this.stock_number = Math.min(res.data[0].stock_number, 999)
      }
    },
    navigateToDeatil(item) {
      this.$navigateTo(`/pagesDetail/commodity/index?box_id=${item.boxId}&from_type=11&series_id=${''}&type=boxGoods&hideMenu=true`)
    },
    // 选择提货商品
    setGoods(item) {
      this.titleIndex = 1
      this.box_bonus_gift = item.box_bonus_gift
      this.goods = item.goods
      this.gifts = (item.gifts || []).map(i => ({ ...i, num: 0 }))
      this.markupGoodses = item.markup_goodses || []
      this.markupGoodses.map(i => {
        if (i.sku_list.length === 1) {
          i.skuName = i.sku_list[0].properties_name.split(';').reduce((a, b) => a.split(':')[1] + '; ' + b.split(':')[1])
        }
      })
    },
    // 改变商品数量
    cartNumChange(e, index) {
      this.gifts[index].num = e
      let num = 0
      this.gifts.map((item) => {
        num += item.num
      })
      this.cartTotalNum = num
      if (this.current === -1) return
      const item = this.markupGoodses[this.current]
      const maxNum = Math.floor(num / item.buy_num) * item.additional_num
      if (maxNum === 0) {
        uni.showToast({
          title: '礼包数量减少，加购商品已清除',
          icon: 'none'
        })
        this.markupGoodses[this.current].count = 0
        this.current = -1
        return
      }
      if (maxNum < item.count) {
        uni.showToast({
          title: '礼包数量减少，加购商品数量已变更',
          icon: 'none'
        })
        this.markupGoodses[this.current].count = maxNum
      }
    },
    // 点击返回
    handelBack() {
      if (this.titleIndex === 1 && this.boxList.length > 1) {
        this.titleIndex = 0
        this.fetchData()
      } else {
        uni.navigateBack()
      }
    },
    // 立即提货
    async handleSubmit() {
      if (this.stock_number === 0) {
        uni.showToast({
          title: '当前库存不足，请发起申购补齐库存再进行提货',
          icon: 'none'
        })
        return
      }
      const goods = this.gifts.filter(i => i.num > 0)
      const shopping_list = []
      if (goods.length < 1) {
        uni.showToast({
          title: '请先选择礼包商品',
          icon: 'none'
        })
        return
      }
      goods.map(item => {
        const data = {
          activity_id: this.goods.activity_id || '',
          goods_id: item.goodsId,
          sku_code: item.goodsSkuId,
          bonus_gift_id: this.box_bonus_gift.bonus_gift_id,
          num: item.num,
          goods_type: item.type || '1',
          pack_type: item.packType || '2',
          from_type: this.goods.from_type + ''
        }
        if (item.packageGoodses && item.packageGoodses.length) {
          data.pack_list = item.packageGoodses.map(el => {
            return {
              sku_code: el.skuCode,
              from_type: 11,
              num: el.packageGoodsNumber
            }
          })
        }
        shopping_list.push(data)
      })
      if (this.current !== -1) {
        const addItem = this.markupGoodses[this.current]
        if (addItem.selectedSkuItem && addItem.selectedSkuItem.order_limit !== 0 && addItem.selectedSkuItem.order_limit < addItem.count) {
          uni.showToast({
            title: `加购商品限购${addItem.selectedSkuItem.order_limit}件`,
            icon: 'none',
            duration: 1500
          })
          return
        }
        if (addItem.selectedSkuItem && addItem.selectedSkuItem.sku_code) {
          const addData = {
            activity_id: '',
            goods_id: addItem.box_additional_id,
            sku_code: addItem.selectedSkuItem.sku_code,
            bonus_gift_id: addItem.bonus_gift_id,
            num: addItem.count,
            goods_type: addItem.goods_type,
            pack_type: addItem.pack_type,
            from_type: '261'
          }
          shopping_list.push(addData)
        }
      }
      const data = JSON.stringify(shopping_list)
      const settleData = {
        is_used_coupon: 1,
        shopping_list: data,
        new_box_order_type: 2,
        stock_goods_id: this.pageQuery.goods_id,
        stock_sku_code: this.pageQuery.sku_code
      }
      const res = await this.$api.orderApi.orderSettle(settleData)
      if (res.success) {
        this.$store.dispatch('setGoodsTemp', {
          shopping_list: data,
          data: res.data,
          settleData
        })
        this.$navigateTo('/pagesBox/pick-up/index?boxType=take')
      }
    },
    // 去选择规格事件
    goSelSku(index, selSku) {
      if (this.current !== index) return
      this.selectedSkuItem = this.markupGoodses[index].selectedSkuItem
      this.hold = false
      setTimeout(() => {
        this.hold = true
      }, 10)
      if (!this.selectedSkuItem || selSku) {
        this.pShow = true
      }
    },
    // 商品勾选事件
    selEvent(index) {
      const item = this.markupGoodses[index]
      if (item.status === 5) return
      if ((Math.floor(this.cartTotalNum / item.buy_num) * item.additional_num) === 0) {
        uni.showToast({
          title: '未满足加购条件，请先添加礼包商品',
          icon: 'none',
          duration: 1500
        })
        return
      }
      if (this.current === index) {
        this.current = -1
        this.selGoods = {}
        this.markupGoodses[index].count = 0
        return
      }
      this.buyCount = 1
      this.$set(this, 'current', index)
      this.markupGoodses[index].count = 1
      this.selGoods = item
      if (item && item.sku_list.length === 1) {
        const temp = item.sku_list[0].properties_name.split(';')
        const nameList = []
        temp.map(item => {
          const itemList = item.split(':')
          nameList.push(itemList[1])
        })
        this.markupGoodses[index].skuName = nameList.join('；')
        if (!this.markupGoodses[index].selectedSkuItem) {
          const obj = {
            activity_id: this.selGoods.activity_id,
            selectText: '',
            director_price: this.selGoods.director_price,
            goods_id: this.selGoods.box_id,
            goods_pic: this.selGoods.pic,
            order_limit: item.sku_list[0].order_limit,
            package_goods_number: 1,
            price: this.selGoods.price,
            properties_name: '',
            num: item.sku_list[0].num,
            region_price: this.selGoods.region_price,
            sku_code: item.sku_list[0].sku_code,
            vip_price: this.selGoods.vip_price
          }
          if (obj && obj.order_limit > 0) {
            obj.order_min = Math.min(item.sku_list[0].order_limit, item.sku_list[0].num)
          } else {
            obj.order_min = item.sku_list[0].num
          }
          console.log('obj.order_min', obj.order_min)
          this.markupGoodses[index].selectedSkuItem = obj
        }
      } else {
        this.goSelSku(index)
      }
    },
    closePopup() {
      const addItem = this.markupGoodses[this.current]
      if (!(addItem.selectedSkuItem && addItem.selectedSkuItem.sku_code)) {
        this.current = -1
      }
      this.$set(this, 'pShow', false)
    },
    alertMax(type) {
      if (type === 'add') {
        const item = this.markupGoodses[this.current].selectedSkuItem || {}
        if (!item) return
        if (item.order_min === item.order_limit) {
          uni.showToast({
            title: '商品限购，无法加购',
            icon: 'none',
            duration: 1500
          })
        } else {
          uni.showToast({
            title: '商品库存不足',
            icon: 'none',
            duration: 1500
          })
        }
      }
    },
    _getUserLevel(item) {
      if (item) {
        return item[getUserLevel()] || item.price || 0
      }
      return 0
    },
    // 点击规格事件
    changeSkuItem(item, flag) {
      if (item) {
        if (item && item.order_limit > 0) {
          item.order_min = Math.min(item.order_limit, item.num)
        } else {
          item.order_min = item.num
        }
        this.markupGoodses[this.current].skuName = item.selectText
        if (item.order_min < this.markupGoodses[this.current].count) {
          this.markupGoodses[this.current].count = 1
          this.buyCount = 1
        }
      } else {
        this.markupGoodses[this.current].skuName = '请选择规格'
      }
      if (this.commodityType === 'boxGoods' && this.isBoxGoodsPackage) return
      this.selectedSkuItem = item
      this.markupGoodses[this.current].selectedSkuItem = item
    },
    // 改变加购商品数量
    addNumChange(e, index) {
      this.markupGoodses[index].count = e
      this.$set(this, 'buyCount', e)
    },
    changeQuantity(num) {
      this.$set(this, 'buyCount', num)
      this.markupGoodses[this.current].count = num
      this.checkOutMax(num)
    },
    checkOutMax(num) {
      const item = this.markupGoodses[this.current]
      if (Number(num) > item.selectedSkuItem.order_min) return
      const maxNum = Math.floor(this.cartTotalNum / item.buy_num) * item.additional_num
      let number = num
      if (maxNum < num) {
        uni.showToast({
          title: '已到达加购上限，请先添加礼包活动数量',
          icon: 'none'
        })
        number = maxNum
      }
      this.$nextTick(() => {
        this.markupGoodses[this.current].count = number
        this.$set(this, 'buyCount', number)
      })
    },
    cartConfirm() {
      this.closePopup()
    }
  }
}
</script>
